<template>
  <div class="categories-container">
    <!-- 搜索表单 -->
    <div class="mb10">
      <SearchForm
        :searchFields="searchItems"
        :maxFirstRowItems="3"
        @search="handleSearch"
        @reset="handleReset"
      />
    </div>

    <!-- 操作按钮 -->
    <div class="mb10">
      <div class="table-operations">
        <a-button
          type="primary"
          @click="addCategory"
        >
          <PlusOutlined /> 新增类目
        </a-button>
        <a-button
          type="primary"
          danger
          :disabled="!hasSelected"
          @click="handleBatchDelete"
        >
          <DeleteOutlined /> 批量删除
        </a-button>
        <span style="margin-left: 8px;" v-if="hasSelected">
          已选择 {{ selectedRowKeys.length }} 项
        </span>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="card-wrap">
      <DataList
        ref="dataListRef"
        :api="(params) => categoryApi.getListByPage(params)"
        :deleteApi="categoryApi.deleteCategory"
        :columns="columns"
        :rowSelection="rowSelection"
        @action="onAction"
      >
        <!-- 自定义列插槽 -->
        <template #name="{ record }">
          <div class="category-name">
            <div class="name-text">{{ record.name }}</div>
          </div>
        </template>



        <template #created_at="{ record }">
          <div>{{ formatDate(record.created_at) }}</div>
        </template>

        <template #updated_at="{ record }">
          <div>{{ formatDate(record.updated_at) }}</div>
        </template>

        <template #action="{ record }">
          <a-space>
            <a-button type="link" size="small" @click="editCategory(record)">
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除这个类目吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" size="small" danger>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </DataList>
    </div>

    <!-- 新增/编辑类目模态框 -->
    <a-modal
      v-model:open="editModalVisible"
      :title="editForm.id ? '编辑类目' : '新增类目'"
      width="600px"
      @ok="handleSave"
      :confirmLoading="saveLoading"
    >
      <a-form
        ref="formRef"
        :model="editForm"
        :rules="editRules"
        layout="vertical"
      >
        <a-form-item label="类目名称" name="name">
          <a-input v-model:value="editForm.name" placeholder="请输入类目名称" />
        </a-form-item>

      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue'
import DataList from '@/components/DataList.vue'
import SearchForm from '@/components/SearchForm.vue'
import { categoryApi } from '@/api/content'
import { formatDate } from '@/utils/date'

// 响应式数据
const dataListRef = ref()
const formRef = ref()
const selectedRowKeys = ref([])
const editModalVisible = ref(false)
const saveLoading = ref(false)

// 编辑表单
const editForm = reactive({
  id: null,
  name: ''
})

// 表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入类目名称', trigger: 'blur' },
    { max: 50, message: '类目名称不能超过50个字符', trigger: 'blur' }
  ]
}

// 搜索表单配置
const searchItems = ref([
  {
    label: '类目名称',
    prop: 'name',
    type: 'input',
    placeholder: '请输入类目名称'
  },
  {
    label: '创建时间',
    prop: 'date_range',
    type: 'daterange',
    placeholder: ['开始日期', '结束日期']
  }
])

// 表格列配置
const columns = [
  {
    title: '类目名称',
    dataIndex: 'name',
    width: 200,
    slot: true
  },

  {
    title: '创建时间',
    dataIndex: 'created_at',
    width: 180,
    slot: true,
    sorter: true
  },
  {
    title: '更新时间',
    dataIndex: 'updated_at',
    width: 180,
    slot: true,
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    type: 'action',
    options: [
      { title: '编辑', key: 'edit' },
      { title: '删除', key: 'delete', type: 'delete' }
    ]
  }
]

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}

// 计算属性
const hasSelected = computed(() => selectedRowKeys.value.length > 0)

// 方法
const onAction = (item, record) => {
  if (item.key === 'edit') {
    editCategory(record)
  }
}

const handleSearch = (params) => {
  // 处理日期范围
  if (params.date_range && params.date_range.length === 2) {
    params.start_date = params.date_range[0]
    params.end_date = params.date_range[1]
    delete params.date_range
  }
  
  dataListRef.value.search(params)
}

const handleReset = () => {
  dataListRef.value.reset()
}

const addCategory = () => {
  editForm.id = null
  editForm.name = ''
  editModalVisible.value = true
}

const editCategory = (record) => {
  editForm.id = record.id
  editForm.name = record.name
  editModalVisible.value = true
}

const handleDelete = async (id) => {
  try {
    await categoryApi.deleteCategory({ id })
    message.success('删除成功')
    dataListRef.value.refreshData()
  } catch (error) {
    message.error('删除失败：' + error.message)
  }
}

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的类目')
    return
  }

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个类目吗？`,
    onOk: async () => {
      try {
        await categoryApi.batchDeleteCategories({ ids: selectedRowKeys.value })
        message.success('批量删除成功')
        selectedRowKeys.value = []
        dataListRef.value.refreshData()
      } catch (error) {
        message.error('批量删除失败：' + error.message)
      }
    }
  })
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    saveLoading.value = true
    
    if (editForm.id) {
      await categoryApi.updateCategory(editForm)
      message.success('更新成功')
    } else {
      await categoryApi.createCategory(editForm)
      message.success('创建成功')
    }
    
    editModalVisible.value = false
    dataListRef.value.refreshData()
  } catch (error) {
    if (error.message) {
      message.error('保存失败：' + error.message)
    }
  } finally {
    saveLoading.value = false
  }
}



// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.categories-container {
  padding: 24px;
}

.category-name {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.name-text {
  font-weight: 500;
  color: #1890ff;
  cursor: pointer;
}



.table-operations {
  display: flex;
  align-items: center;
  gap: 8px;
}


</style>